package webserver;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.SimpleTimeZone;

@SuppressWarnings("serial")
public class Response extends HashMap<String, String> {
	byte[] bytes = null;
	String code;
	String reason;
	boolean isHEAD = false;
	
	public Response(boolean isHEAD) {
		this.isHEAD = isHEAD;
		SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(new SimpleTimeZone(0, "GMT"));
		dateFormat.setCalendar(cal);
	}
	
	public void setHeader(String header, String value) {
		put(header, value);
	}
	
	public void setCode(String code) {
		this.code = code;
	}
	
	public void setReason(String reason) {
		this.reason = reason;
	}
	
	public void setBytes(byte[] bytes) {
		this.bytes = bytes;
		put("Content-Length", Integer.toString(bytes.length));
	}
	
	public String getCode() {
		return code;
	}
	
	public byte[] getHeader() {
		StringBuilder sb = new StringBuilder("HTTP/1.1 ");
		sb.append(code);
		sb.append(" ");
		sb.append(reason);
		sb.append("\r\n");
		
		for (Map.Entry<String, String> entry: this.entrySet()) {
			sb.append(entry.getKey());
			sb.append(": ");
			sb.append(entry.getValue());
			sb.append("\r\n");
		}
		sb.append("\r\n");
		
		return sb.toString().getBytes();
	}
	
	public byte[] getBytes() {
		byte[] header = getHeader();
		byte[] output;
		if (isHEAD) {
			output = header;
		} else {
			output = new byte[header.length + bytes.length];
			System.arraycopy(header, 0, output, 0, header.length);
			System.arraycopy(bytes, 0, output, header.length, bytes.length);
		}

		return output;
	}
}
